/*
 * @Author: 码农 2646995216@qq.com
 * @Date: 2025-03-03 23:54:14
 * @LastEditors: 码农 2646995216@qq.com
 * @LastEditTime: 2025-03-04 22:53:18
 * @FilePath: /pthread/pthread_cond.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

 #include<iostream>
 #include<unistd.h>
 #include<pthread.h>
 #include<string>
 #include<vector>


 using namespace std;

 class ThreadDate
 {
 public:
	 ThreadDate(int num)
	 {
		 threadname="thread_"+to_string(num);
	 }
 
 public:
	 string threadname;//线程的名字
 };

pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;//定义锁
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;//定义条件变量
int count=0;

void* thread(void* args)
{
	ThreadDate* td=static_cast<ThreadDate*>(args);
	const char* name=td->threadname.c_str();
    while(true)
	{
		pthread_mutex_lock(&mutex);//加锁
		pthread_cond_wait(&cond,&mutex);//线程申请到了锁，并且进入队列后，释放锁，在队列中等待唤醒信号
		cout<<"I am a "<<name<<", count:"<<count++<<endl;
        pthread_mutex_unlock(&mutex);//解锁
	}
}

 int main()
 {
	vector<ThreadDate*> threads;
	vector<pthread_t> tids;//存储线的tid

	for(int i=1;i<=5;i++)
	{
		pthread_t tid;
		ThreadDate* data=new ThreadDate(i);
		threads.push_back(data);
		pthread_create(&tid,nullptr,thread,(void*)threads[i-1]);//创建线程
		tids.push_back(tid);
		cout<<"create "<<data->threadname.c_str()<<endl;
	}

	sleep(3);

	while(true)
	{
		sleep(1);
		cout<<"开始唤醒一个"<<endl;
		pthread_cond_signal(&cond);//将队列中的线程一个一个唤醒
		//pthread_cond_broadcast(&cond)；将队列中的线程全部唤醒
	}
    
	for(auto thread:tids)
	{
	   pthread_join(thread,nullptr);//回收线程
    }

    for(auto del:threads)
	{
		delete del;
	}

	return 0;
 }
